package com.rongshu.view.userInfo.fragment;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;

import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseFragment;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.userInfo.activity.CollectedSerializeAcitivity;
import com.rongshu.view.userInfo.activity.EditCollectedWorksActivity;
import com.rongshu.view.userInfo.adapter.SerializeAdapter;
import com.rongshu.view.userInfo.entity.Article;
import com.rongshu.view.userInfo.iview.ArticleView;
import com.rongshu.view.userInfo.listener.OnItemFunctionClickListener;
import com.rongshu.view.userInfo.presenter.ArticlePresenter;
import com.rongshu.widget.BanyanDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

import static android.app.Activity.RESULT_OK;

public class SerializeFragment extends BaseFragment<ArticlePresenter> implements ArticleView, OnItemFunctionClickListener {
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.collected_works_recyclerview)
    RecyclerView collected_works_recyclerview;
    @BindView(R.id.layout_empty)
    RelativeLayout layout_empty;

    //manager
    private LinearLayoutManager manager = null;
    //adapter
    private SerializeAdapter mSerializeAdapter = null;
    //文集id
    private int article_id = 0;
    //request
    private final int EDIT_REQUEST_CODE = 0x01;
    //dialog
    private BanyanDialog dialog = null;
    //intent
    private Intent intent = null;
    //map
    private Map<String, Object> map = null;
    private int pageIndex = 1;
    private int pageSize = 10;
    //refresh,load
    private boolean isrefresh = true;

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_serialize_view;
    }

    @Override
    protected void initViews() {
        //set presenter
        setPresenter(new ArticlePresenter(getActivity()), this);
        //layoutmanager
        manager = new LinearLayoutManager(getActivity());
        //adapter
        mSerializeAdapter = new SerializeAdapter(getActivity());
        mSerializeAdapter.setOnItemFunctionClickListener(this);
        //recyclerview
        collected_works_recyclerview.setLayoutManager(manager);
        collected_works_recyclerview.setAdapter(mSerializeAdapter);
        //触发自动刷新
        refreshLayout.autoRefresh();
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                isrefresh = true;
                pageIndex = 1;
                refreshLayout.resetNoMoreData();
                getAppSerial();
                refreshlayout.finishRefresh(2000, false);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                isrefresh = false;
                pageIndex++;
                getAppSerial();
                refreshlayout.finishLoadmore(2000, false);
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    /**
     * App获取连载名字列表
     */
    private void getAppSerial() {
        int user_id = UserInfoUtils.getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("isSerial", "true");
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        presenter.getAppSerial(user_id, "true", pageIndex, pageSize, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * APP修改文集
     */
    private void getUpdateSerial(int serial_id, String serial_name) {
        int user_id = UserInfoUtils.getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("serial_id", serial_id);
        map.put("serial_name", serial_name);
        presenter.getUpdateSerial(user_id, serial_id, serial_name, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * APP删除文集
     */
    private void getDeleteSerial(int serial_id) {
        int user_id = UserInfoUtils.getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("serial_id", serial_id);
        presenter.getDeleteSerial(user_id, serial_id, Common.encryptionSign(map));
        map.clear();
    }

    @Override
    public void onClick(int position, int serial_id, String title) {
        intent = new Intent(getActivity(), CollectedSerializeAcitivity.class);
        intent.putExtra(Constant.INTENT_MESSAGE, serial_id);
        intent.putExtra(Constant.INTENT_TITLE, title);
        startActivity(intent);
    }

    @Override
    public void onEditClick(int position, int article_id, String title) {
        //记录
        this.article_id = article_id;
        //intent
        intent = new Intent(getActivity(), EditCollectedWorksActivity.class);
        intent.putExtra(Constant.INTENT_TITLE, title);
        startActivityForResult(intent, EDIT_REQUEST_CODE);
    }

    @Override
    public void onDeleteClick(int position, final int count, final int serial_id) {
        //dialog
        BanyanDialog.Builder builder = new BanyanDialog.Builder(getActivity());
        builder.setTitle(count == 0 ? "提示" : "无法删除");
        builder.setContent(count == 0 ? "确定要删除当前连载嘛" : "请先删除该连载中所有文章");
        builder.setLeft(count == 0 ? "取消" : "我知道了");
        if (count == 0) {
            builder.setRight("确定");
        }
        builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
            @Override
            public void leftClickListener() {
                dialog.dismiss();
            }

            @Override
            public void rightClickListener() {
                dialog.dismiss();
                if (count == 0) {
                    //删除文集
                    getDeleteSerial(serial_id);
                }
            }
        });
        dialog = builder.create();
        dialog.show();
    }

    @Override
    public void onArticleList(Article article) {
        if (article == null) {
            return;
        }
        List<Article.ResponseBean> authorDetailBeans = article.getResponse();
        if (mSerializeAdapter != null) {
            if (isrefresh) {
                refreshLayout.finishRefresh();
                if (authorDetailBeans == null || authorDetailBeans.isEmpty()) {
                    refreshLayout.setVisibility(View.GONE);
                    layout_empty.setVisibility(View.VISIBLE);
                } else {
                    refreshLayout.setVisibility(View.VISIBLE);
                    layout_empty.setVisibility(View.GONE);
                    mSerializeAdapter.setArticles(authorDetailBeans);
                    mSerializeAdapter.notifyDataSetChanged();
                }
            } else {
                if (authorDetailBeans == null || authorDetailBeans.isEmpty()) {
                    refreshLayout.finishLoadmoreWithNoMoreData();
                } else {
                    refreshLayout.finishLoadmore();
                    mSerializeAdapter.addArticles(authorDetailBeans);
                    mSerializeAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Override
    public void onUpdateArticle(INetBean iNetBean) {
        isrefresh = true;
        pageIndex = 1;
        getAppSerial();
    }

    @Override
    public void onAddArticle(INetBean bean) {

    }

    @Override
    public void onDeleteArticle(INetBean bean) {
        isrefresh = true;
        pageIndex = 1;
        getAppSerial();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case EDIT_REQUEST_CODE:
                    String edit_content = data.getStringExtra(Constant.INTENT_MESSAGE);
                    getUpdateSerial(article_id, edit_content);
                    break;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (dialog != null) {
            dialog.cancel();
            dialog.dismiss();
            dialog = null;
        }
    }
}
